package org.sunshinebox.team.sweettest;

import java.lang.reflect.Field;
import java.util.LinkedList;
import java.util.List;

import org.junit.After;
import org.junit.Before;

public class TestSupport implements InstanceManipulator {
	
	private Tools tools;
	private Field[] inheritTestFields;
	
	@Before
	public void setup(){
		getTools().setup();
		before();
	}
	
	protected void before() {}
	protected void after(){}
	
	@After
	public void verify(){
		after();
		getTools().verify();
	}
	
	
	public Tools getTools() {
		if (tools == null){
			tools = Tools.createWithManipulator(this);
		}
		return tools;
	}
	
	private Field[] getInheritTestFields() {
		if (inheritTestFields == null){
			inheritTestFields = this.getClass().getDeclaredFields();
		}
		return inheritTestFields;
	}
	
	public List<Field> getFieldAnnotatedWith(Class annotationClass) {
		List<Field> fieldList = new LinkedList<Field>();
		for (Field field : getInheritTestFields()) {
			if (field.getAnnotation(annotationClass) != null)
				fieldList.add(field);
		}
		
		return fieldList;
	}

	public void setFieldValue(Field field, Object value) {
		try {
			field.set(this, value);
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
	}

	public Object getFieldValue(Field field) {
		try {
			return field.get(this);
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return null;
	}

	public void arm() {
		getTools().arm();
	}
}
